import { Manager } from "@/models/Manager";
import * as argon2 from "argon2";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { z } from "zod";
import { sign } from "hono/jwt";

const authRoute = new Hono();

const loginSchema = z.object({
  username: z.string(),
  password: z.string(),
});

authRoute.post("/login", async (c) => {
  let body = await c.req.parseBody();
  let result = loginSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  //   查询是否存在
  let num = await Manager.countBy({ username: result.data.username });

  if (num === 0) {
    throw new HTTPException(400, { message: "用户名不存在" });
  }

  let manager = await Manager.findOneBy({ username: result.data.username });

  let success = await argon2.verify(manager.password, result.data.password);

  if (!success) {
    throw new HTTPException(400, { message: "密码错误" });
  }

  //   生成token
  const payload = {
    sub: manager.id,
    exp: Math.floor(Date.now() / 1000) + 60 * 60 * 5, // 令牌在5小时后过期
  };

  const secret = process.env.SECRET;
  const token = await sign(payload, secret);
  return c.json({ code: 200, message: "登陆成功", data: { token } });
});

export default authRoute;
